package com.file.system.controller.system;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.file.system.entity.dict.DataRange;
import com.file.system.entity.dict.IsSuperAdmin;
import com.file.system.entity.res.CommonResult;
import com.file.system.entity.res.DataTree;
import com.file.system.entity.system.*;
import com.file.system.plugin.shiro.ShiroTools;
import com.file.system.plugin.validated.SQLInjectionValidation;
import com.file.system.service.system.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static cn.hutool.core.util.ObjectUtil.notEqual;
import static java.util.Objects.isNull;


/**
 * 树
 *
 * @author jch
 */
@RestController
@Validated
@RequestMapping("/tree")
public class WebTreeController {

    @Autowired
    private IWebDepartmentService iWebDepartmentService;
    @Autowired
    private IWebDictionaryValService iWebDictionaryValService;
    @Autowired
    private IWebMenuService iWebMenuService;
    @Autowired
    private IWebRoleDataService iWebRoleDataService;
    @Autowired
    private IWebRoleNodeService iWebRoleNodeService;
    @Autowired
    private ShiroService shiroService;


    /**
     * 通过编码查询树（所有业务）
     *
     * @param code 数据权限树编码
     * @return CommonResult
     * @apiNote -
     * @author 靳春晖
     */
    @PostMapping("/get/{code}")
    public CommonResult all(@PathVariable
                            @NotEmpty(message = "编码不能为空")
                            @SQLInjectionValidation(fieldName = "编码")
                            String code) {
        //获取登录用户
        WebUser user = ShiroTools.getShiroUser();

        //查询用户所有角色id
        List<Long> roleList = shiroService.getUserRoleIds(user.getId());

        if (notEqual(user.getIsSuperAdmin(), IsSuperAdmin.YES.val) && roleList.isEmpty()) {
            return CommonResult.ok().setText("未分配角色");
        }

        List<WebRoleData> roleDataList = null;
        if (notEqual(user.getIsSuperAdmin(), IsSuperAdmin.YES.val)) {
            //查询所有角色数据权限
            roleDataList = iWebRoleDataService.list(new QueryWrapper<WebRoleData>()
                    .in("fk_role_id", roleList)
                    .eq("is_del", "0")
                    .eq("code", code)
            );
        }

        List list = new ArrayList<>();
        List<Long> nodeList = new ArrayList<>();
        //非管理员未找到数据权限，返回null
        if (notEqual(user.getIsSuperAdmin(), IsSuperAdmin.YES.val) && CollectionUtil.isEmpty(roleDataList)) {
            return CommonResult.ok().setResult(list);
        }

        //用户没有查询当前树的全部权限，查询自定义权限
        if (notEqual(user.getIsSuperAdmin(), IsSuperAdmin.YES.val) &&
                !roleDataList.stream().anyMatch(l -> ObjectUtil.equal(l.getDictDataRange(), DataRange.ALL.val))
        ) {
            //查询所有角色配置该树的节点
            List<WebRoleNode> roleNodeList = iWebRoleNodeService.list(new QueryWrapper<WebRoleNode>()
                    .eq("a.code", code)
                    .in("a.fk_role_id", roleList)
            );
            //角色没有配置树节点
            if (CollectionUtil.isEmpty(roleNodeList)) {
                return CommonResult.ok().setResult(null);
            }
            //返回普通用户配置树节点
            nodeList = roleNodeList.stream().map(WebRoleNode::getFkNodeId).distinct().collect(Collectors.toList());
        }

        switch (code) {
            //部门
            case "department":
                list = department(nodeList);
                break;
            default:
                break;
        }

        return CommonResult.ok().setResult(list);
    }


    /**
     * 查询所有部门
     */
    private List<WebDepartment> department(List<Long> nodeList) {
        QueryWrapper<WebDepartment> query = new QueryWrapper<>();
        //判断nodeList是否为空，不为空则添加查询条件
        query.in(nodeList.size() > 0, "a.id", nodeList);
        //添加查询条件：is_del = 0
        query.eq("a.is_del", "0");
        //添加排序条件：sort升序
        query.orderByAsc("a.sort");

        //调用iWebDepartmentService的list方法，查询数据
        List<WebDepartment> list = iWebDepartmentService.list(query);
        return list;
    }


    /**
     * 懒加载
     */
    private List<DataTree> lazy(DataTree dataTree, List<DataTree> results) {
        if (!isNull(dataTree) && ObjectUtil.isNotNull(dataTree.getPid())) {
            results = results.stream().filter(l -> ObjectUtil.equal(dataTree.getPid(), l.getPid())).collect(Collectors.toList());
        }
        return results;
    }

    /**
     * 设置树是否有子节点
     */
    private List<DataTree> setIsLeft(List<DataTree> results) {
        for (DataTree tree : results) {
            // 遍历结果，获取每一个DataTree
            long count = results.stream()
                    // 过滤出id等于当前DataTree的id的DataTree
                    .filter(l -> ObjectUtil.equal(tree.getId(), l.getPid()))
                    // 计算出满足条件的DataTree的数量
                    .count();
            // 设置当前DataTree的叶子节点属性
            tree.setLeaf(count > 0);
        }
        return results;
    }
}

